package com.enzo.prms.common.base.web;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import org.apache.struts2.dispatcher.StrutsResultSupport;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class StringResultType extends StrutsResultSupport {
    private static final Logger LOG = LoggerFactory.getLogger(StrutsResultSupport.class);
    private static final long serialVersionUID = 1L;
    private String contentTypeName;
    private String result = "result";


    @Override
    protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
        HttpServletResponse response = (HttpServletResponse) invocation
                .getInvocationContext().get(HTTP_RESPONSE);
        String contentType = conditionalParse(contentTypeName, invocation);
        if (contentType == null) {
            contentType = "application/json; charset=UTF-8";
        }
        response.setContentType(contentType);
        response.setHeader("Cache-Control", "no-store");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            String resultValue = (String) invocation.getStack().findValue(result);
            if(resultValue==null){
                resultValue = getDefaultResultValue();
            }
            pw.println(resultValue);
        } catch (Exception e) {
            LOG.error("Result execution occur error.");
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

    public String getContentTypeName() {
        return contentTypeName;
    }

    public void setContentTypeName(String contentTypeName) {
        this.contentTypeName = contentTypeName;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getDefaultResultValue() {
        return "{\"success\":true}";
    }

}
